import React, { useEffect, useState } from "react";
import { modalPropsType, warehouseTypes } from "@/constants/types";
import { Modal, Form, Input, Select } from "antd";
import { useRequest } from "ahooks";
import XlCheckBox from "@/components/Form/XlCheckBox";
import XlRadio from "@/components/Form/XlRadio";
import { useModel } from "@umijs/max";
import XlSelect from "@/components/Form/XlSelect";
import XlNumberRange from "@/components/Form/XlNumberRange";
import { fetchDomesticWhOptions, fetchServiceProviderOptions, fetchDestinationOptions } from "@/pages/BasicInfo/services";
import { fetchLpsLineTagDetail } from "../../services";
import { isArray } from "@/utils/verify";
import { isEmptyObj } from "@/utils/util";

const {Item} = Form;
const rules = [{required: true}];
const labelCol = {span: 4}

const ProductTagUpdate = ({visible, currentRow, onCancel, onSubmit, loading, title}: modalPropsType) => {
  const [form] = Form.useForm();
  const {getDict} = useModel('dictModel');
  const countrys = getDict('country');
  const prdList = getDict('prdType');
  const transportTypes = getDict('transportType');
  const sports = getDict('sport');
  const dports = getDict('dport');
  const deliveryMethods = getDict('deliveryMethod');
  const destTypes = getDict('destType');
  const dispFlag = getDict('dispFlag');
  const {data: warehouseList} = useRequest(async () => {
    const res = await fetchDomesticWhOptions();
    return (res || [])?.map((v: warehouseTypes) => ({label: v?.name, value: v?.code}))
  });
  const {data: shipCodes} = useRequest(async () => {
    const res = await fetchServiceProviderOptions({type: 'ship'});
    return (res || []).map((v: {name: string, code: string}) => ({label: v?.name, value: v?.code}));
  });
  const {runAsync: fetchCodesApi} = useRequest(async (params: {country: string; destType: string}) => {
    const res = await fetchDestinationOptions(params);
    return (res || []).map((v: string) => ({label: v, value: v}));
  }, {manual: true});
  const [codes, setCodes] = useState([]);
  

  const searchCodes = async (params: { country: string; destType: string }) => {
    const res = await fetchCodesApi(params);
    setCodes(res || []);
  }

  const fields = [
    {
      label: '运输方式',
      name: "transportType",
      isSingle: true,
      comp: <XlRadio.ButtonRadioGutterGroup options={transportTypes} />,
      rules,
      options: transportTypes,
    },
    {
      label: '国家',
      name: "country",
      isSingle: true,
      comp: <XlRadio.ButtonRadioGutterGroup options={countrys} 
        // onChange={(val: {value: string}) => searchCodes({country: val.value, destType: form.getFieldValue('destType')})}
       />,
      rules,
      options: countrys,
    },
    {
      label: '产品',
      name: "prdType",
      isSingle: true,
      comp: <XlRadio.ButtonRadioGutterGroup options={prdList} />,
      rules,
      options: prdList,
    },
    {
      label: '船司',
      name: "shipCode",
      comp: <XlCheckBox.ButtonGutterGroup options={shipCodes} />,
      options: shipCodes,
    },
    {
      label: '起始地',
      name: "sport",
      comp: <XlCheckBox.ButtonGutterGroup options={sports} />,
      options: sports,
    },
    {
      label: '目的港',
      name: "dport",
      comp: <XlCheckBox.ButtonGutterGroup options={dports} />,
      options: dports,
    },
    {
      label: '收货仓库',
      name: "cwh",
      comp: <XlCheckBox.ButtonGutterGroup options={warehouseList} />,
      options: warehouseList,
    },
    {
      label: '派送方式',
      name: "deliveryMethod",
      comp: <XlCheckBox.ButtonGutterGroup options={deliveryMethods} />,
      options: deliveryMethods,
    },
    {
      label: '目的地类型',
      name: "destType",
      isSingle: true,
      comp: <XlRadio.ButtonRadioGutterGroup options={destTypes} 
      //onChange={(val: {value: string}) => searchCodes({country: form.getFieldValue('country'), destType: val.value})}
       />,
      options: destTypes, 
    },
    {
      label: '目的地',
      name: "destCode",
      comp: <Input.TextArea rows={5} />,
      options: codes, 
    },
    {
      label: '价格',
      name: "price",
      comp: <XlNumberRange />,
    },
  ];

  const handleSubmit = async () => {
    const res = await form.validateFields();
    const list = fields.filter(v => !!res?.[v.name] || res?.[v.name] === 0);
    const arr: any [] = [];
    list.forEach(v => {
      const val = res?.[v.name];
      // 如果为价格
      if (v.name === 'price') {
        arr.push({
          conditionCode: 'priceStart',
          conditionValues: val?.[0] || val?.[0] === 0  ? [val?.[0]] : [],
          conditionLabels: val?.[0] || val?.[0] === 0  ? [val?.[0]] : [],
        });
        arr.push({
          conditionCode: 'priceEnd',
          conditionValues: val?.[1] || val?.[1] === 0  ? [val?.[1]] : [],
          conditionLabels: val?.[1] || val?.[1] === 0  ? [val?.[1]] : []
        });
      } if (v.name === 'destCode') {
        arr.push({
          conditionCode: 'destCode',
          conditionValues: val?.replace(/，|\s|\n|\//g, ',').split(',').filter((v: string) => v.trim()),
          conditionLabels: val?.replace(/，|\s|\n|\//g, ',').split(',').filter((v: string) => v.trim()),
        });
      } else {
        // 为其他
        arr.push({
          conditionCode: v.name,
          conditionValues: isArray(val) ? val : [val],
          conditionLabels: (isArray(val) ? val : [val]).map((key: string|number) => v?.options?.find((o: {label: string, value: string | number}) => o.value === key)?.label),
        });
      }

    });
    onSubmit({
      name: res?.name,
      dispFlag: res?.dispFlag,
      marketingTags: res?.marketingTags,
      conditions: arr
    });
  }

  useEffect(() => {
    const destType = form.getFieldValue('destType');
    const country = form.getFieldValue('country');
    searchCodes({destType, country});
  }, [form.getFieldValue('destType'), form.getFieldValue('country')]);


  useEffect(() => {
    if (currentRow?.id) {
      fetchLpsLineTagDetail({id: currentRow?.id}).then(res => {
        const singleSelects = fields.filter((v: any) => v.isSingle).map(v => v.name);
        const price = (res?.conditions || []).filter((v: any) => v?.conditionCode === "priceStart" || v?.conditionCode === "priceEnd");
        const priceObj: any = {};
        if (price && price.length > 0) {
          price.forEach((v: any) => {
            if (v?.conditionValues.length > 0) {
              priceObj[v?.conditionCode] = v?.conditionValues?.[0];
            }
          })
        }
        const priceArr: any [] = [];
        if (priceObj.priceStart || priceObj.priceStart === 0) {
          priceArr.push(priceObj.priceStart);
        }
        if (priceObj.priceEnd || priceObj.priceEnd === 0) {
          priceArr.push(priceObj.priceEnd);
        }
        form.setFieldsValue({
          name: res?.name,
          dispFlag: res?.dispFlag,
          marketingTags: res?.marketingTags,
          ...(res?.conditions || []).reduce((p: any, v: any) => {
            if (v?.conditionCode === "priceStart" || v?.conditionCode === "priceEnd") {
              return p;
            }
            if (v?.conditionCode === "destCode") {
              return {
                ...p,
                [v.conditionCode]: v?.conditionValues?.join(',')
              }
            }
            if (singleSelects.includes(v.conditionCode)) {
              return {
                ...p,
                [v.conditionCode]: v?.conditionValues?.[0]
              }
            }
            return {
              ...p,
              [v.conditionCode]: v?.conditionValues
            }
          }, {}),
          price: priceArr
        });
      })
    }
  }, [currentRow?.id])

  return (
    <Modal
      title={title}
      open={visible}
      onCancel={onCancel}
      maskClosable={false}
      confirmLoading={loading}
      width="750px"
      onOk={handleSubmit}
    >
      <Form form={form} labelCol={labelCol} className="modal-form-padding">
        <Item label="产品分类标签" name="name" rules={rules}>
          <Input />
        </Item>
        <Item label="标签可见" name="dispFlag" rules={rules}>
          <Select options={dispFlag} />
        </Item>
        <Item label="营销标签" name="marketingTags" rules={rules}>
          <Input />
        </Item>
        {
          fields?.map(v => {
            if (v.name !== 'destCode') {
              return (
                <Item key={v.name} label={v.label} name={v.name} rules={v.rules}>
                  {v.comp}
                </Item>
              );
            }
            return (
              <Item noStyle shouldUpdate={(prev, next) => prev.country !== next.country || prev.destType !== next.destType}>
                {({getFieldsValue}) => {
                  const values = getFieldsValue();
                  if (!values.country || !values.destType) {
                    return '';
                  }
                  return (
                    <Item key={v.name} label={v.label} name={v.name} rules={v.rules}>
                      {v.comp}
                    </Item>
                  );
                }}
              </Item>
            );
          })
        }
      </Form>
    </Modal>
  );
}
export default ProductTagUpdate;